using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesUtilitiesCOAClaimableExpense : System.Web.UI.Page
{
    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected DataObj CurPageDataObj = new DataObj();

    #region ResultTable
    protected DataTable ResultTable
    {
        get
        {
            return (DataTable)ViewState["ResultTable"];
        }

        set
        {
            ViewState["ResultTable"] = value;
        }
    }
    #endregion

    #region GridViewHeader
    protected ArrayList GridViewHeader
    {
        get
        {
            return (ArrayList)ViewState["GridViewHeader"];
        }

        set
        {
            ViewState["GridViewHeader"] = value;
        }
    }
    #endregion

    #region ErrorMessage
    protected string ErrorMessage
    {
        get
        {
            return ViewState["ErrorMessage"].ToString();
        }

        set
        {
            ViewState["ErrorMessage"] = value;
        }
    }
    #endregion

    #region UpdatedMessage
    protected string UpdatedMessage
    {
        get
        {
            return ViewState["UpdatedMessage"].ToString();
        }

        set
        {
            ViewState["UpdatedMessage"] = value;
        }
    }
    #endregion

    #region Moded
    protected string Moded
    {
        get
        {
            return ViewState["MOD"].ToString();
        }

        set
        {
            ViewState["MOD"] = value;
        }
    }
    #endregion

    #region InternalID
    protected string InternalID
    {
        get
        {
            return ViewState["InternalID"].ToString();
        }

        set
        {
            ViewState["InternalID"] = value;
        }
    }
    #endregion

    #region DeletionFailedMessage
    protected string DeletionFailedMessage
    {
        get
        {
            return ViewState["DeletionFailedMessage"].ToString();
        }

        set
        {
            ViewState["DeletionFailedMessage"] = value;
        }
    }
    #endregion

    #region SAMessage
    protected string SAMessage
    {
        get
        {
            return ViewState["SAMessage"].ToString();
        }

        set
        {
            ViewState["SAMessage"] = value;
        }
    }
    #endregion

    #region DuplicateSAMessage
    protected string DuplicateSAMessage
    {
        get
        {
            return ViewState["DuplicateSAMessage"].ToString();
        }

        set
        {
            ViewState["DuplicateSAMessage"] = value;
        }
    }
    #endregion

    #region EditLink
    protected string EditLink
    {
        get
        {
            return ViewState["EditLink"].ToString();
        }

        set
        {
            ViewState["EditLink"] = value;
        }
    }
    #endregion

    #region DeleteLink
    protected string DeleteLink
    {
        get
        {
            return ViewState["DeleteLink"].ToString();
        }

        set
        {
            ViewState["DeleteLink"] = value;
        }
    }
    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        this.SwitchLanguage();
        this.DataDelete();

        if (!IsPostBack)
        {
            //this.SwitchLanguage();
            this.PageComponentSetup();
            this.Moded = "Add";
            this.DataEdit();
            this.LoadDataBinding();
        }
    }
    #endregion

    #region Button_Submit_Click
    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        if (this.DataValidate())
        {
            using (GLClaimTypeManager CurGLClaimTypeManager = new GLClaimTypeManager(this.CurrentPrivateSession))
            {
                bool smooth = false;
                if (this.Moded.CompareTo("Update") == 0)
                    smooth = CurGLClaimTypeManager.UpdateClaimTypeByID(this.InternalID, this.TextBox_ACCDesc.Text.Trim(), (chk_Active.Checked) ? "1" : "0");
                else
                    smooth = CurGLClaimTypeManager.AddNewClaimType(this.TextBox_ACCCode.Text.Trim(), this.TextBox_ACCDesc.Text.Trim());
                    
                if (smooth)
                {
                    //log down the history
                    this.CurLogManager.LogMessage("[GonzalesUtilitiesCOAClaimableExpense] : Acc. Code (" + this.TextBox_ACCCode.Text.Trim() + ", Acc. Name: " + this.TextBox_ACCDesc.Text.Trim() + ") added ", this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                    this.ShowMessage(this.UpdatedMessage);

                    this.LoadData();
                    if (this.ResultTable != null)
                    {
                        DataView ResultView = new DataView(this.ResultTable);
                        ResultView.Sort = this.CurPageDataObj.AccountCode + " ASC";
                        this.BindData(ResultView);
                    }
                    this.ResetData(); // reset text
                }
                else
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesUtilitiesCOAClaimableExpense.Button_Submit_Click] : Failed atCurGLClaimTypeManager.AddNewClaimType('" + this.TextBox_ACCCode.Text.Trim() + "', '" + this.TextBox_ACCDesc.Text.Trim() + "') : " + CurGLClaimTypeManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage(this.ErrorMessage + LogID);
                }
            }
        }
    }
    #endregion

    #region Button_Cancel_Click
    protected void Button_Cancel_Click(object sender, EventArgs e)
    {
        this.ResetData();
    }
    #endregion

    #region Button_Import_Click
    protected void Button_Import_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.FileUploadSource.PostedFile != null && this.FileUploadSource.PostedFile.FileName.Length > 0)
            {
                FileFactory.FileFactory ff = new FileFactory.FileFactory(this.CurrentPrivateSession);
                if (ff.StartWatching(this.FileUploadSource.PostedFile.InputStream, "A", this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.Entity.InternalID))
                    this.LoadDataBinding();
                else
                    this.ShowErrorMessage(ff.LoggedMessages[0].ToString());
            }
            else
            {
                this.ShowErrorMessage("Invalid File");
            }
        }
        catch (Exception)
        {
            // do nothing
        }
    }
    #endregion

    #region OnRowCreated
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection cells = e.Row.Cells;

            for (int i = 0; i < this.GridViewHeader.Count; i++)
            {
                cells[i].Text = this.GridViewHeader[i].ToString();
            }
        }
    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {

        // browse button
        //this.Button_Browse.Attributes["onclick"] = "ShowModal('AddressBook', document.getElementById('ModalResult')); return false;";
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.lbl_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.lbl_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.lbl_AddNew.Text = CurLanguageFactory.DisplayValue("AddNew");

                this.lbl_AccountCode.Text = CurLanguageFactory.DisplayValue("AccountCode");
                this.lbl_AccountDesc.Text = CurLanguageFactory.DisplayValue("AccountDescription");
                this.chk_Active.Text = CurLanguageFactory.DisplayValue("AccountState");
                
                
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");
                // Create GridView
                this.GridViewHeader = new ArrayList();
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("gvh_AccountCode"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("gvh_AccountDescription"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("gvh_AccountState"));
                
                this.EditLink = CurLanguageFactory.DisplayValue("EditLink");
                this.DeleteLink = CurLanguageFactory.DisplayValue("DeleteLink");
                // default
                this.ErrorMessage = CurLanguageFactory.DisplayValue("ErrorMessage");
                this.UpdatedMessage = CurLanguageFactory.DisplayValue("UpdatedMessage");
                this.DeletionFailedMessage = CurLanguageFactory.DisplayValue("DeletionFailedMessage");
                this.SAMessage = CurLanguageFactory.DisplayValue("SAMessage");
                this.DuplicateSAMessage = CurLanguageFactory.DisplayValue("DuplicateSAMessage");
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesUtilitiesCOAClaimableExpense.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

    #region ShowMessage
    protected void ShowMessage(string Message)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = Message;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "MessageBox";
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData
    protected void LoadData()
    {
        using (GLClaimTypeManager CurGLClaimTypeManager = new GLClaimTypeManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultObj = CurGLClaimTypeManager.GetAllClaimType();

                if (ResultObj != null)
                {
                    this.ResultTable = new DataTable();

                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.AccountCode, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.AccountDescription, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.AcountActive, Type.GetType("System.String")));
                    
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.EditLink, Type.GetType("System.String")));
                    this.ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.DeleteLink, Type.GetType("System.String")));

                    for (int x = 0; x < ResultObj.Count; x++)
                    {
                        DataRow ResultRow = this.ResultTable.NewRow();

                        //ResultRow[this.CurPageDataObj.internalID] = ((GLClaimType)ResultObj[x]).InternalID;
                        ResultRow[this.CurPageDataObj.AccountCode] = ((GLClaimType)ResultObj[x]).GLCode;
                        ResultRow[this.CurPageDataObj.AccountDescription] = ((GLClaimType)ResultObj[x]).DisplayName;
                        ResultRow[this.CurPageDataObj.AcountActive] = (((GLClaimType)ResultObj[x]).State) ? "<img src='" + GonzalesImages.Icon_Checked + "'>" : "";

                        ResultRow[this.CurPageDataObj.EditLink] = "<a class='GridViewLink' href='GonzalesUtilitiesCOAClaimableExpense.aspx?EDIT=TRUE&id=" + ((GLClaimType)ResultObj[x]).InternalID + "' >" + this.EditLink + "</a>";
                        ResultRow[this.CurPageDataObj.DeleteLink] = "<a class='GridViewLink' href='GonzalesUtilitiesCOAClaimableExpense.aspx?DELETE=TRUE&id=" + ((GLClaimType)ResultObj[x]).InternalID + "' onclick=\"return confirm('This action will not able to be undone, continue?');\">" + this.DeleteLink + "</a>";

                        this.ResultTable.Rows.Add(ResultRow);
                    } 
                }
                else
                {
                    this.CurLogManager.LogError("[GonzalesUtilitiesCOAClaimableExpense.LoadData] : Failed at : " + CurGLClaimTypeManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }
        
    }
    #endregion    

    #region LoadDataBinding
    protected void LoadDataBinding()
    {
        this.LoadData();
        if (this.ResultTable != null)
        {
            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.CurPageDataObj.AccountCode + " ASC";

            this.BindData(ResultView);
        }
    }
    #endregion

    #region DataDelete
    protected void DataDelete()
    {
        bool smooth = true;
        if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36 &&
            Request.QueryString["DELETE"] != null && Request.QueryString["DELETE"].CompareTo("TRUE") == 0)
        {
            using (GLClaimTypeManager CurGLClaimTypeManager = new GLClaimTypeManager(this.CurrentPrivateSession))
            {
                if (!(smooth = CurGLClaimTypeManager.DeleteClaimTypeByID(Request.QueryString["id"])))
                {
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesUtilitiesCOAClaimableExpense.DataDelete] : Failed at  CurGLClaimTypeManager.DeleteClaimTypeByID(Request.QueryString['" + Request.QueryString["id"] + "']) : " + CurGLClaimTypeManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage(this.DeletionFailedMessage + LogID);
                }
            }

            if (smooth)
            {
                Response.Redirect("GonzalesUtilitiesCOAClaimableExpense.aspx");
            }
        }
    }

    #endregion

    #region DataEdit
    protected void DataEdit()
    {
        if (Request.QueryString["id"] != null && Request.QueryString["id"].Length == 36 &&
            Request.QueryString["EDIT"] != null && Request.QueryString["EDIT"].CompareTo("TRUE") == 0)
        {
            using (GLClaimTypeManager CurGLClaimTypeManager = new GLClaimTypeManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection CurrGLClaimType = CurGLClaimTypeManager.GetClaimTypeByID(Request.QueryString["id"]);
                this.InternalID = Request.QueryString["id"];

                if (CurrGLClaimType != null && CurrGLClaimType.Count == 1)
                {
                    // Set values project ------

                    this.TextBox_ACCCode.Text = ((GLClaimType)CurrGLClaimType[0]).GLCode;
                    this.TextBox_ACCDesc.Text = ((GLClaimType)CurrGLClaimType[0]).DisplayName;
                    this.chk_Active.Checked = ((GLClaimType)CurrGLClaimType[0]).State;
                    this.TextBox_ACCCode.ReadOnly = true;
                    this.Moded = "Update";
                    try
                    {
                        using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
                        {
                            this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Update");
                        }
                    }
                    catch (Exception ex)
                    {
                        this.CurLogManager.LogError("[GonzalesUtilitiesCOAClaimableExpense.DataEdit.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
                    }
                }
                else
                {   // Edit error
                    string LogID = SwissArmy.UniqueID();
                    this.CurLogManager.LogError(LogID, "[GonzalesUtilitiesCOAClaimableExpense.DataEdit] : Failed at  CurGLClaimTypeManager.GetClaimTypeByID(Request.QueryString['" + Request.QueryString["id"] + "']) : " + CurGLClaimTypeManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                    this.ShowErrorMessage(this.DeletionFailedMessage + LogID);
                }
            }
        }
    }
    #endregion

    #region ResetData
    protected void ResetData()
    {
        this.InternalID = string.Empty;
        this.TextBox_ACCCode.Text = string.Empty;
        this.TextBox_ACCDesc.Text = string.Empty;
        this.chk_Active.Checked = true;
        this.Moded = "Add";
        this.TextBox_ACCCode.ReadOnly = false;
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesUtilitiesCOAClaimableExpense.Button_Cancel_Click.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }
    }
    #endregion

    #region DataValidate
    protected bool DataValidate()
    {
        bool valid = true;
        if (this.Moded.CompareTo("Update") == 0) return valid;

        StringBuilder ErrorMessages = new StringBuilder("<ul>");

        if (this.TextBox_ACCCode.Text.Trim().Length == 0)
        {
            valid = false;
            ErrorMessages.AppendLine("<li>" + this.SAMessage + "</li>");
        }

        // check if having duplicate entry
        if (this.ResultTable != null)
        {
            foreach (DataRow ResultRow in this.ResultTable.Rows)
            {
                if (ResultRow[this.CurPageDataObj.AccountCode].ToString().CompareTo(this.TextBox_ACCCode.Text.Trim()) == 0)
                {
                    valid = false;
                    ErrorMessages.AppendLine("<li>" + this.DuplicateSAMessage + "</li>");
                    break;
                }
            }
        }

        ErrorMessages.AppendLine("</ul>");

        if (!valid) this.ShowErrorMessage(ErrorMessages.ToString());

        return valid; 
    }
    #endregion

    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    #endregion

    #region Class: DataObj

    protected class DataObj
    {
        public readonly string internalID = "internal_id";
        public readonly string AccountCode = "claimtype_id";
        public readonly string AccountDescription = "claimtype_desc";
        public readonly string AcountActive = "claim_state";
        
        public readonly string EditLink = "EditLink";
        public readonly string DeleteLink = "DeleteLink";
    }

    #endregion

}
